<template>
  <page-container :scrollY="false">
    <search-form
      v-model="searchForm"
      :searchColumns="searchColumns"
      :searchOptions="{ menuSpan: 10 }"
      @on-search="handleSearch">
      <template v-slot:newBtn>
        <el-button
          type="primary"
          @click="handleAddForm('add')"
          >新增人群名称</el-button
        >
      </template>
    </search-form>

    <avue-table
      :dataList="dataList"
      :loading="loading"
      :page="page"
      :tableColumns="tableColumns"
      :tableOptions="{ menu: true, menuWidth: 140 }"
      @onPageChange="onPageChange">
      <template v-slot:menu="{ row }">
        <el-button
          type="primary"
          icon="el-icon-edit"
          circle
          @click="handleAddForm('edit', row)">
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-view"
          circle
          @click="handleView(row)">
        </el-button>
      </template>
    </avue-table>
  </page-container>
</template>

<script>
import tableMixins from '@/mixins/table'
import { deepClone } from '@/utils'
import { mapGetters } from 'vuex'
import { searchColumns, tableColumns } from './config/table-config'
import { allDialogForm } from './config/dialog-config'
import { queryCrowdRule, addCrowdRuleForm, editCrowdRuleForm } from '@/api/userManage'

export default {
  mixins: [tableMixins],
  data() {
    return {
      actionType: 'add',
      piePayList: [],
      pieUserList: [],
      dataList: [],
      childList: [],
      diaForm: {
        peopleType: [],
      },
      searchForm: {
        dateRange: [this.$startStamp(new Date()), this.$endStamp(new Date())],
      },
      editForm: {},
    }
  },
  computed: {
    ...mapGetters(['commonData', 'device']),
    userList() {
      return this.commonData?.userList ?? []
    },
    allDialogForm,
    searchColumns,
    tableColumns,
  },
  methods: {
    async getList() {
      this.dataList = []

      const searchParams = this.formatSearch()
      const queryParams = {
        ...searchParams,
        page: this.page.currentPage,
        page_size: this.page.pageSize,
      }

      this.loading = true

      const { data } = await queryCrowdRule(queryParams)
      this.dataList = data?.list ?? []
      this.piePayList = data?.pie?.pay ?? []
      this.pieUserList = data?.pie?.user ?? []
      this.page.total = data?.total ?? 0
      this.summaryData = data ?? {}

      this.loading = false
    },
    // 查询参数格式化
    formatSearch() {
      const searchParams = deepClone(this.searchForm)
      const [start, end] = this.searchForm.dateRange
      searchParams.start = start && this.$dayjs(this.$startStamp(start)).unix()
      searchParams.end = end && this.$dayjs(this.$endStamp(end)).unix()
      delete searchParams.dateRange
      return searchParams
    },
    handleAddForm(type, row) {
      let formData = {
        peopleType: [],
      }

      formData = deepClone(this.diaForm)
      if (type === 'edit') {
        formData = deepClone(row)
        const rule = row.rule
        let peopleType = []
        for (let keys in rule) {
          const name = {
            ['count']: 1,
            ['amount']: 2,
            ['day']: 3,
          }
          if (keys === 'day') {
            peopleType.push({
              v1: name[keys],
              // v2: keyChil,
              day: rule[keys],
            })
            for (let keyChil in rule[keys]) {
              peopleType.push({
                v1: name[keys],
                v2: keyChil,
                day: rule[keys][keyChil],
              })
            }
          } else {
            for (let keyChil in rule[keys]) {
              peopleType.push({
                v1: name[keys],
                v2: keyChil,
                day: rule[keys][keyChil],
              })
            }
          }
        }
        formData.peopleType = peopleType
      }
      this.$dialogForm.show({
        title: `${type === 'add' ? '新增' : '编辑'}人群名称`,
        data: formData,
        option: {
          span: 24,
          labelWidth: 120,
          column: this.allDialogForm,
        },
        callback: async ({ data, close }) => {
          let resData = {}
          const t_parms = this.getData(data?.peopleType)
          const parm = {
            ...data,
            rule: t_parms,
          }
          delete parm.peopleType
          if (type === 'add') {
            resData = await addCrowdRuleForm(parm)
          } else {
            resData = await editCrowdRuleForm(parm)
          }

          if (resData.code === 0) {
            this.$message.success(`${type === 'add' ? '新增' : '编辑'}成功`)
          }
          this.getList()
          close()
        },
      })
    },
    getData(newVal) {
      const parms = deepClone(newVal)
      const name = {
        [1]: 'count',
        [2]: 'amount',
        [3]: 'day',
      }
      let obj = {}
      let objs = {}
      const t_parm = parms?.map(item => {
        if (item?.v1 === 1) {
          this.$set(obj, item?.v2, Number(item?.day))
        }
        if (item?.v1 === 2) {
          this.$set(objs, item?.v2, Number(item?.day * 10000))
        }

        return {
          [name[item?.v1]]: item?.v1 === 3 ? Number(item?.day) : item?.v1 === 2 ? objs : obj,
        }
      })
      let t_no = {}
      t_parm.forEach(item => {
        Object.keys(item).filter(it => this.$set(t_no, it, item[it]))
      })
      return JSON.stringify(t_no)
    },
    handleView(row) {
      this.$router.push({
        path: '/user/crowd_user',
        query: { name: row?.name, id: row?.id },
      })
    },
  },
  mounted() {
    this.handleSearch()
  },
}
</script>

<style lang="scss" scoped></style>
